package com.kamistoat.meimeimall.meimeimallproduct.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Sentinel自定义配置
 * 希望在Sentinel进行流量拒绝时，返回自定义数据--该功能要求必须实现BlockExceptionHandler接口的handle方法
 */
@Configuration
public class ProductSentinelConfig implements BlockExceptionHandler {
    /**
     * 重写BlockExceptionHandler接口的handle方法。
     * @param httpServletRequest 请求
     * @param httpServletResponse 响应
     * @param e 流控信息
     * @throws Exception
     */
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
//        // 构建一个R对象
//        R blocked = R.error(BizCodeEnum.BLOCKED_BY_SENTINEL.getCode(), BizCodeEnum.BLOCKED_BY_SENTINEL.getMessage());
//        // 设置响应的编码信息
//        httpServletResponse.setCharacterEncoding("UTF-8");
//        httpServletResponse.setContentType("application/json");
//        // 把这个R对象写到响应中去
//        httpServletResponse.getWriter().write(JSON.toJSONString(blocked));
        // 也可以给这个响应设置重定向路径。一般是流量过大时，重定向到一个提示用户等待的页面
        httpServletResponse.sendRedirect("http://meimeimall.com/blockWait.html");
    }
}
